import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Scanner;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class TcpEchoServer {
    private ServerSocket serverSocket=null;

    public TcpEchoServer(int port) throws IOException {
        serverSocket =new ServerSocket(port);
    }
    public  void start() throws IOException {
        System.out.println("启动服务器");
        ExecutorService service= Executors.newCachedThreadPool();
        while (true){
            Socket client=serverSocket.accept();
            service.submit(new Runnable() {
                @Override
                public void run() {
                    try {
                        processConnection(client);
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
        }
    }
    public void  processConnection(Socket client) throws IOException {
        System.out.printf("%s:%s\n",client.getInetAddress(),client.getPort());
        try(InputStream in=client.getInputStream();
            OutputStream out=client.getOutputStream()){
            while (true){
                Scanner scanner=new Scanner(in);
                if(!scanner.hasNext()){
                    System.out.println("客户段下线");
                    break;
                }
                String req=scanner.next();

                String resp=process(req);
                PrintWriter printWriter=new PrintWriter(out);
                printWriter.println(resp);
                printWriter.flush();
            }
        }catch (IOException e){
          e.printStackTrace();
        }finally {
            client.close();
//
//            try{
//                client.close();
//
//            }catch (IOException e){
//                e.printStackTrace();
//
//            }

        }
    }
    public String process(String req){
        return req;
    }

    public static void main(String[] args) throws IOException {
        TcpEchoServer server=new TcpEchoServer(9090);
        server.start();


    }
}
